package com.lagou.config;

import com.lagou.io.Resources;
import com.lagou.pojo.Configuration;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;


import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * @author: jie.zhao
 * @create: 2021/01/24 10:29
 */
public class XmlConfigBuilder {

    private Configuration configuration;

    public XmlConfigBuilder() {
        this.configuration = new Configuration();
    }

    /**
     * 解析配置文件,封装对象
     * @param inputStream
     * @return
     */
    public Configuration parseConfig(InputStream inputStream) throws DocumentException, PropertyVetoException {
        // 解析
        XmlMapperBuilder xmlMapperBuilder = new XmlMapperBuilder();
        SAXReader reader = new SAXReader();
        Document document = reader.read(inputStream);
        Properties properties = new Properties();
        Element root = document.getRootElement();
        List<Element> propertyList = root.selectNodes("//property");
        for (Element element:propertyList){
            String key = element.attribute("name").getValue();
            String value = element.attribute("value").getValue();
            properties.put(key,value);
        }

        // 封装
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
        comboPooledDataSource.setUser(properties.getProperty("username"));
        comboPooledDataSource.setPassword(properties.getProperty("password"));
        comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        configuration.setDataSource(comboPooledDataSource);


        // 解析mapper.xml
        List<Element> mapperList = root.selectNodes("//mapper");
        for (Element element:mapperList){
            String mapperPath = element.attribute("resource").getValue();
            InputStream mapperInputStream = Resources.getFileAsInputStream(mapperPath);
            xmlMapperBuilder.parseConfig(configuration,inputStream);
        }

        return configuration;
    }
}
